<script setup lang="ts">
import { reactive, ref, toRefs } from 'vue'
import type { ElForm } from 'element-plus'
import { FormItemType, ParamsType, DictionaryType } from '@/common/types/conf'
const props = defineProps<{
  params: ParamsType
  form: FormItemType[]
  dictionary: DictionaryType
}>()

const emit = defineEmits<{
  (e: 'search'): void
  (e: 'update:params', data?: ParamsType): void
}>()

const { params } = toRefs(props)
const data = reactive({
  params: params.value
})

const onSearch = () => {
  const { params } = toRefs(data)
  emit('update:params', { ...params.value })
  emit('search')
}

const searchForm = ref<InstanceType<typeof ElForm>>()
const onReset = () => {
  searchForm.value?.resetFields();
  emit('update:params')
  emit('search')
}

// 自定义筛选项 设置 params
const setParams = (key: string, value: string | number): void => {
  data.params[key] = value;
}
defineExpose({ setParams })
</script>

<template>
  <el-form ref="searchForm" :inline="true" :model="data.params">
    <el-form-item v-for="formItem in form" :key="formItem.searchKey" :prop="formItem.searchKey">
      <el-input
        v-if="formItem.type === 'input'"
        v-model="data.params[formItem.searchKey]"
        :placeholder="formItem.tip"
      ></el-input>

      <el-select
        v-if="formItem.type === 'select'"
        v-model="data.params[formItem.searchKey]"
        :placeholder="formItem.tip"
      >
        <el-option
          :label="label"
          :value="value"
          v-for="{ label, value } in dictionary[formItem.searchKey]"
          :key="label"
        ></el-option>
      </el-select>

      <!-- 自定义筛选项：筛选数据通过 ref 获取 setParams 方法来设置筛选参数 -->
      <template v-if="formItem.type === 'custom'">
        <slot :name="formItem.searchKey"></slot>
      </template>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSearch">查询</el-button>
      <el-button @click="onReset">重置</el-button>
      <slot name="button"></slot>
    </el-form-item>
  </el-form>
</template>

<style scoped></style>